package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart=shoppingCartMapper.select(BaseContext.getCurrentId(),shoppingCartDTO);
        //判断是否已经存在，如果存在则购物对车应物品number+1,否则插入这条数据
        if (shoppingCart==null){
            shoppingCart=new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
            shoppingCart.setAmount(BigDecimal.ONE);
            shoppingCartMapper.insert(shoppingCart);
        }else {
            shoppingCart.setNumber(shoppingCart.getNumber()+1);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
            shoppingCart.setAmount(BigDecimal.ONE);
            shoppingCartMapper.update(shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> list() {
        Long userId=BaseContext.getCurrentId();
        return shoppingCartMapper.selectByUserId(userId);
    }

    @Override
    public void clean() {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.cleanByUserId(userId);
    }

    @Override
    public void deleteOne(ShoppingCartDTO shoppingCartDTO) {
        //若商品number==1,则直接删除该数据；否则number-1
        ShoppingCart shoppingCart = shoppingCartMapper.select(BaseContext.getCurrentId(), shoppingCartDTO);

        shoppingCart.setNumber(shoppingCart.getNumber()-1);

        shoppingCartMapper.deleteOne(BaseContext.getCurrentId(),shoppingCart);
        if (shoppingCart.getNumber()>0){
            shoppingCartMapper.insert(shoppingCart);
        }

    }
}
